package com.example.demo.web;

import com.aliyun.com.viapi.FileUtils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ocr.model.v20191230.RecognizeBusinessLicenseRequest;
import com.aliyuncs.ocr.model.v20191230.RecognizeBusinessLicenseResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.example.demo.bean.Result;
import com.example.demo.util.ResHelper;
import com.example.demo.vo.BusinessLicenseRecognizeResult;
import com.google.gson.Gson;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by ZhaoYuJie on 2018/7/2.
 */
@RestController
@RequestMapping(value = "/aliyun",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(value = "阿里云服务接口")
public class ALiYunCtrl {
    @Value("${aliyun.access.key}")
    private String accessKey;
    @Value("${aliyun.access.secret}")
    private String accessKeySecret;


    @ApiOperation(
            value = "智能识别营业执照" ,
            notes = "* 控制台->企业认证",
            response = Void.class,produces = "application/json",position = 1)
    @ApiResponses({
            @ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 1, message = "操作失败")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name="businessLicenseUrl",value = "营业执照URL",paramType = "query",dataType = "string")
    })
    @GetMapping(value = "/v1.1/entities/idents/recognizeBusinessLicense")
    public Result<BusinessLicenseRecognizeResult> recognizeBusinessLicense(@RequestParam String businessLicenseUrl) throws Exception {
        FileUtils fileUtils = FileUtils.getInstance(accessKey,accessKeySecret);
        String ossurl = fileUtils.upload(businessLicenseUrl);

        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
//        request.setRegionId("cn-shanghai");
        request.setImageURL(ossurl);

        BusinessLicenseRecognizeResult result = new BusinessLicenseRecognizeResult();

        try {
            RecognizeBusinessLicenseResponse response = client.getAcsResponse(request);
            System.out.println("============"+new Gson().toJson(response));
            BeanUtils.copyProperties(response.getData(),result);
        } catch (Exception e) {
            throw new IllegalArgumentException("智能识别营业执照失败，"+e.getMessage());
        }

        return ResHelper.success(result);
    }


}
